<?php
session_start();
require_once("../basicInfo/user.php");
/**other variables */
$passwordIsValid = true;
$FirstNameIsEmpty = false;
$LastNameIsEmpty = false;
$UserNameIsEmpty = false;
$EmailIsEmpty = false;
$passwordIsEmpty = false;
$password2IsEmpty = false;
$UserNameIsUnique = true;
$FileError=false;

//file size
define ("MAX_SIZE","100");

//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

//file error message
$error="";

//image name if exists
$image_name="";

/** Check that the page was requested from itself via the POST method. */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/** Check whether the user has filled in the first name in the text field "First Name" */
    if ($_POST["fname"]=="") {
        $FirstNameIsEmpty = true;
    }

    if ($_POST["lname"]=="") {
        $LastNameIsEmpty = true;
    }
    if ($_POST["email"]=="") {
        $EmailIsEmpty = true;
    }
    if ($_POST["uname"]=="") {
        $UserNameIsEmpty = true;
    }

    $userId = UserController::get_user_id_by_username($_POST["uname"]);
    if ($userId) {
        $UserNameIsUnique = false;
    }

    /** Check whether a password was entered and confirmed correctly */
    if ($_POST["password"]=="")
        $passwordIsEmpty = true;
    if ($_POST["password2"]=="")
        $password2IsEmpty = true;
    if ($_POST["password"]!=$_POST["password2"]) {
        $passwordIsValid = false;
    }

    //reads the name of the file the user submitted for uploading
    $image=$_FILES['image']['name'];


     //if it is not empty
if ($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file, otherwize we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
//print error message
$error .= "Unknown extension!";
$FileError=true;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
$error .= "You have exceeded the size limit!";
$FileError=true;
}

//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="../../upload/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
$error .= "Copy unsuccessfull!";
//$error .= $_FILES['tmp_name']['error'].
$FileError=true;
}
}
}


    /** Check whether the boolean values show that the input data was validated successfully.
     * If the data was validated successfully, add it as a new entry in the database.
     * After adding the new entry, close the connection
     */
    if (!$FirstNameIsEmpty && !$LastNameIsEmpty && !$UserNameIsEmpty && !$EmailIsEmpty && $UserNameIsUnique && !$passwordIsEmpty && !$password2IsEmpty && $passwordIsValid && !$FileError) {
        UserController::create_user($_POST["fname"],$_POST["lname"],$_POST["uname"],$_POST["email"], $_POST["password"],$image_name);
        $userinfo=UserController::obtain_user($_POST["uname"]);
        $serialzedUser = serialize($userinfo);
        $_SESSION['userinfo']=$serialzedUser;
        $_SESSION['logged_in']="true";
        echo '<script language="javascript">location.replace("profile.php");</script>';
        //header('Location: profile.php' );
        exit;
    }
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
    $fullr = array("First_Name" => $_POST["fname"],"Last_Name" => $_POST["lname"],"User_Name" => $_POST["uname"],"Email" => $_POST["email"],
        "Password" => $_POST["password"]);
else
    $fullr = array("First_Name" => "","Last_Name" => "","User_Name" => "","Email" => "",
        "Password" => "");
?>


 <?php include "../../layout/header.php"; ?>

<?php include "../../layout/navleft.php"; ?>
<div id="content_small"><div class="container_brown">
        <br><br>
<center><img src="images/register.jpg" alt="REGISTER" /></center>
<br><br>
<form action="register.php" method="POST" enctype="multipart/form-data">
<table align="center">
            <tr><td><b>FIRST NAME</b></td><td><input type="text" name="fname" value="<?php echo $fullr['First_Name'];?>"></td></tr>
                <?php
                                /** Display error messages if "First Name" field is empty*/
                                if ($FirstNameIsEmpty) {
                                    echo ("<tr><td></td><td><span style = 'color:red; font-weight:bold;'>First Name is required.</span></td></tr>");


                                }
                                    ?>
            <tr><td><b>LAST NAME</b></td><td><input type="text" name="lname" value="<?php echo $fullr['Last_Name'];?>"></td></tr>
                <?php
                                /** Display error messages if "First Name" field is empty*/
                                if ($LastNameIsEmpty) {
                                    echo ("<tr><td></td><td><span style = 'color:red; font-weight:bold;'>Last Name is required.</span></td></tr>");

                                }
                                ?>
            <tr><td><b>USERNAME</b></td><td><input type="text" name="uname" value="<?php echo $fullr['User_Name'];?>"></td></tr>
                <?php
                                /** Display error messages if "First Name" field is empty*/
                                if ($UserNameIsEmpty) {
                                    echo ("<tr><td></td><td><span style = 'color:red; font-weight:bold;'>User Name is required.</span></td></tr>");

                                }
                                if (!$UserNameIsUnique) {
                                    echo ("<tr><td></td><td><span style = 'color:red; font-weight:bold;'>UserName already exists. Please check and try again.</span></td></tr>");

                                }
                                ?>
            <tr><td><b>PASSWORD</b></td><td><input type="password" name="password"></td></tr>
            <tr><td><b>CONFIRM PASSWORD</b></td><td><input type="password" name="password2">
                <?php
                                /** Display error messages if the "password2" field is empty
                                 * or its contents do not match the "password" field
                                 */
                                if ($password2IsEmpty |$passwordIsEmpty ) {
                                    echo ("<tr><td></td><td><span style = 'color:red; font-weight:bold;'>Password is required and Confirm your password, please.</span></td></tr>");

                                }?>&nbsp
                                <?php
                                if (!$password2IsEmpty && !$passwordIsEmpty && !$passwordIsValid) {
                                    echo ("<tr><td></td><td><span style = 'color:red; font-weight:bold;'>The passwords do not match!</span></td></tr>");

                                }
                                ?>
            <tr><td><b>EMAIL ADDRESS</b></td><td><input type="text" name="email" value="<?php echo $fullr['Email'];?>"></td></tr>
                <?php
                                /** Display error messages if "First Name" field is empty*/
                                if ($EmailIsEmpty) {
                                    echo ("<tr><td></td><td><span style = 'color:red; font-weight:bold;'>Email is required.</span>&nbsp</td></tr>");

                                }?>
            <!--<tr><td><b>Gender</b></td><td><input type="radio" name="sex" value="m" checked="checked"/> Male&nbsp&nbsp<input type="radio" name="sex" value="f" /> Female</td></tr>-->
          
            <tr><td><b>UPLOAD IMAGE</b></td><td><input type="file" name="image"></td></tr>
            <?php
                                /** Display error messages if "First Name" field is empty*/
                                if ($FileError) {
                                    echo ("<tr><td></td><td><span style = 'color:red; font-weight:bold;'>".$error."</span>&nbsp</td></tr>");

                                }?>
                                
</table>
<br>
<br>
        <center>I certify that I have read <a href="PrivacyPolicy.htm" target="_blank" >Privacy Policy</a></center>
        <center><input type="image" src="images/signup.jpg" alt="SIGNUP" /></center>

        <br>
</form>
    </div></div>
    
    <?php include "../../layout/navright.php"; ?>
<?php include "../../layout/footer.php"; ?>
